<template>
  <div class="check-plan-container">
    <h2>盘点计划管理</h2>
    
    <el-card class="filter-card">
      <div class="filter-controls">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索计划名称"
          size="small"
          style="width: 200px"
          clearable
          @keyup.enter="loadPlanData"
        >
          <template #append>
            <el-button @click="loadPlanData" size="small"><i class="el-icon-search"></i></el-button>
          </template>
        </el-input>
        
        <el-select v-model="planStatus" placeholder="计划状态" size="small" @change="loadPlanData">
          <el-option label="全部状态" value="all"></el-option>
          <el-option label="未开始" value="pending"></el-option>
          <el-option label="进行中" value="processing"></el-option>
          <el-option label="已完成" value="completed"></el-option>
          <el-option label="已取消" value="cancelled"></el-option>
        </el-select>
        
        <el-select v-model="planType" placeholder="计划类型" size="small" @change="loadPlanData">
          <el-option label="全部类型" value="all"></el-option>
          <el-option label="月度盘点" value="monthly"></el-option>
          <el-option label="季度盘点" value="quarterly"></el-option>
          <el-option label="年度盘点" value="yearly"></el-option>
          <el-option label="部门盘点" value="dept"></el-option>
          <el-option label="专项盘点" value="special"></el-option>
        </el-select>
        
        <el-button type="primary" size="small" @click="createPlan">新建计划</el-button>
        <el-button type="info" size="small" @click="importPlan">导入计划</el-button>
        <el-button type="warning" size="small" @click="exportPlan">导出计划</el-button>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        :data="planData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column prop="planNo" label="计划编号" width="150" fixed="left"></el-table-column>
        <el-table-column prop="planName" label="计划名称" width="250"></el-table-column>
        <el-table-column prop="planType" label="计划类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getPlanTypeTagType(scope.row.planType)">
              {{ getPlanTypeText(scope.row.planType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planScope" label="盘点范围" width="150">
          <template #default="scope">
            {{ scope.row.planScope || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAssets" label="计划数量" width="100" align="center"></el-table-column>
        <el-table-column prop="checkedAssets" label="已盘数量" width="100" align="center"></el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="100" align="center">
          <template #default="scope">
            <el-progress :percentage="parseInt(scope.row.completionRate)" :show-text="false" size="small"></el-progress>
            <span>{{ scope.row.completionRate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="startPlan(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              启动
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="completePlan(scope.row)"
              v-if="scope.row.status === 'processing'"
            >
              完成
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="cancelPlan(scope.row)"
              v-if="['pending', 'processing'].includes(scope.row.status)"
            >
              取消
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="editPlan(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="viewPlanDetail(scope.row)"
              v-if="scope.row.status !== 'pending'"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 计划表单对话框 -->
    <el-dialog
      v-model="planDialogVisible"
      :title="isEditMode ? '编辑盘点计划' : '新建盘点计划'"
      width="700px"
      @close="resetPlanForm"
    >
      <el-form :model="planForm" :rules="planFormRules" ref="planFormRef" label-width="120px">
        <el-form-item label="计划编号" v-if="isEditMode">
          <el-input v-model="planForm.planNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="请输入计划名称"></el-input>
        </el-form-item>
        <el-form-item label="计划类型" prop="planType">
          <el-select v-model="planForm.planType" placeholder="请选择计划类型">
            <el-option label="月度盘点" value="monthly"></el-option>
            <el-option label="季度盘点" value="quarterly"></el-option>
            <el-option label="年度盘点" value="yearly"></el-option>
            <el-option label="部门盘点" value="dept"></el-option>
            <el-option label="专项盘点" value="special"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点范围" prop="planScope">
          <el-select v-model="planForm.planScope" placeholder="请选择盘点范围" multiple collapse-tags>
            <el-option label="全部资产" value="all"></el-option>
            <el-option label="IT部门" value="IT部门"></el-option>
            <el-option label="财务部" value="财务部"></el-option>
            <el-option label="人力资源部" value="人力资源部"></el-option>
            <el-option label="市场部" value="市场部"></el-option>
            <el-option label="行政部" value="行政部"></el-option>
            <el-option label="研发部" value="研发部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="planForm.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="planForm.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="planForm.manager" placeholder="请输入负责人"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="planForm.remark" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="planDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePlan">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 计划详情对话框 -->
    <el-dialog
      v-model="planDetailDialogVisible"
      title="计划详情"
      width="700px"
    >
      <div v-if="currentPlanDetail" class="plan-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="计划编号">{{ currentPlanDetail.planNo }}</el-descriptions-item>
          <el-descriptions-item label="计划名称">{{ currentPlanDetail.planName }}</el-descriptions-item>
          <el-descriptions-item label="计划类型">
            <el-tag :type="getPlanTypeTagType(currentPlanDetail.planType)">
              {{ getPlanTypeText(currentPlanDetail.planType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="盘点范围">{{ currentPlanDetail.planScope || '-' }}</el-descriptions-item>
          <el-descriptions-item label="计划数量">{{ currentPlanDetail.totalAssets }}</el-descriptions-item>
          <el-descriptions-item label="已盘数量">{{ currentPlanDetail.checkedAssets }}</el-descriptions-item>
          <el-descriptions-item label="完成率">
            <el-progress :percentage="parseInt(currentPlanDetail.completionRate)" :show-text="false" size="small"></el-progress>
            <span>{{ currentPlanDetail.completionRate }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ currentPlanDetail.startDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ currentPlanDetail.endDate }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentPlanDetail.manager || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentPlanDetail.creator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentPlanDetail.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentPlanDetail.status)">
              {{ getStatusText(currentPlanDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentPlanDetail.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="planDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import axios from 'axios'

export default {
  name: 'CheckPlan',
  setup() {
    const searchKeyword = ref('')
    const planStatus = ref('all')
    const planType = ref('all')
    const planData = ref([])
    const selectedPlans = ref([])
    
    // 分页数据
    const pagination = ref({
      currentPage: 1,
      pageSize: 20,
      total: 0
    })
    
    // 对话框状态
    const planDialogVisible = ref(false)
    const planDetailDialogVisible = ref(false)
    const isEditMode = ref(false)
    
    // 表单数据
    const planForm = ref({
      planName: '',
      planType: '',
      planScope: [],
      startDate: '',
      endDate: '',
      manager: '',
      remark: ''
    })
    
    // 表单规则
    const planFormRules = reactive({
      planName: [
        { required: true, message: '请输入计划名称', trigger: 'blur' }
      ],
      planType: [
        { required: true, message: '请选择计划类型', trigger: 'change' }
      ],
      planScope: [
        { required: true, message: '请选择盘点范围', trigger: 'change' }
      ],
      startDate: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ],
      endDate: [
        { required: true, message: '请选择结束日期', trigger: 'change' }
      ],
      manager: [
        { required: true, message: '请输入负责人', trigger: 'blur' }
      ]
    })
    
    const planFormRef = ref(null)
    const currentPlanDetail = ref(null)
    
    // 加载计划数据
    const loadPlanData = async () => {
      try {
        const params = {
          keyword: searchKeyword.value,
          status: planStatus.value === 'all' ? '' : planStatus.value,
          type: planType.value === 'all' ? '' : planType.value,
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize
        }
        
        const response = await axios.get('/api/check/plans', {
          params
        })
        
        if (response.code === 200 && response.data) {
          planData.value = response.data.list || []
          pagination.value.total = response.data.total || 0
        } else {
          // 使用模拟数据
          setMockPlanData()
        }
      } catch (error) {
        console.error('获取盘点计划数据失败:', error)
        setMockPlanData()
      }
    }
    
    // 设置模拟计划数据
    const setMockPlanData = () => {
      // 生成模拟数据
      const mockData = []
      const statuses = ['pending', 'processing', 'completed', 'cancelled']
      const planTypes = ['monthly', 'quarterly', 'yearly', 'dept', 'special']
      
      for (let i = 1; i <= 50; i++) {
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const type = planTypes[Math.floor(Math.random() * planTypes.length)]
        const totalAssets = Math.floor(Math.random() * 1000) + 100
        const checkedAssets = status === 'pending' ? 0 : 
                            status === 'completed' ? totalAssets : 
                            Math.floor(Math.random() * totalAssets)
        const completionRate = totalAssets > 0 ? 
                              Math.round((checkedAssets / totalAssets) * 100) + '%' : '0%'
        
        mockData.push({
          id: i,
          planNo: `CP${new Date().getFullYear()}${String(i).padStart(6, '0')}`,
          planName: `${getPlanTypeText(type)}计划${i}`,
          planType: type,
          planScope: type === 'dept' ? 'IT部门,财务部' : '全部资产',
          totalAssets,
          checkedAssets,
          completionRate,
          startDate: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          endDate: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          creator: `用户${Math.floor(Math.random() * 10) + 1}`,
          createTime: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')} ${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
          status
        })
      }
      
      // 根据筛选条件过滤数据
      let filteredData = [...mockData]
      if (planStatus.value !== 'all') {
        filteredData = filteredData.filter(item => item.status === planStatus.value)
      }
      if (planType.value !== 'all') {
        filteredData = filteredData.filter(item => item.planType === planType.value)
      }
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        filteredData = filteredData.filter(item => 
          item.planName.toLowerCase().includes(keyword)
        )
      }
      
      // 分页处理
      const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
      const end = start + pagination.value.pageSize
      planData.value = filteredData.slice(start, end)
      pagination.value.total = filteredData.length
    }
    
    // 选中项变化
    const handleSelectionChange = (selection) => {
      selectedPlans.value = selection
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      pagination.value.currentPage = 1
      loadPlanData()
    }
    
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      loadPlanData()
    }
    
    // 新建计划
    const createPlan = () => {
      isEditMode.value = false
      resetPlanForm()
      planDialogVisible.value = true
    }
    
    // 编辑计划
    const editPlan = (plan) => {
      isEditMode.value = true
      planForm.value = {
        ...plan,
        startDate: plan.startDate ? new Date(plan.startDate) : '',
        endDate: plan.endDate ? new Date(plan.endDate) : ''
      }
      planDialogVisible.value = true
    }
    
    // 保存计划
    const savePlan = async () => {
      if (!planFormRef.value) return
      
      try {
        await planFormRef.value.validate()
        
        const planData = {
          ...planForm.value,
          startDate: planForm.value.startDate ? planForm.value.startDate.toISOString().split('T')[0] : '',
          endDate: planForm.value.endDate ? planForm.value.endDate.toISOString().split('T')[0] : '',
          planScope: Array.isArray(planForm.value.planScope) ? planForm.value.planScope.join(',') : planForm.value.planScope
        }
        
        // 模拟API调用
        console.log(isEditMode.value ? '更新计划:' : '创建计划:', planData)
        
        planDialogVisible.value = false
        loadPlanData()
        
        ElMessage.success(isEditMode.value ? '更新成功' : '创建成功')
      } catch (error) {
        console.error('保存计划失败:', error)
        ElMessage.error('保存失败')
      }
    }
    
    // 启动计划
    const startPlan = (plan) => {
      ElMessageBox.confirm(`确定要启动计划「${plan.planName}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟API调用
          console.log('启动计划:', plan)
          
          loadPlanData()
          ElMessage.success('计划启动成功')
        } catch (error) {
          console.error('启动计划失败:', error)
          ElMessage.error('启动失败')
        }
      }).catch(() => {})
    }
    
    // 完成计划
    const completePlan = (plan) => {
      ElMessageBox.confirm(`确定要完成计划「${plan.planName}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟API调用
          console.log('完成计划:', plan)
          
          loadPlanData()
          ElMessage.success('计划已完成')
        } catch (error) {
          console.error('完成计划失败:', error)
          ElMessage.error('操作失败')
        }
      }).catch(() => {})
    }
    
    // 取消计划
    const cancelPlan = (plan) => {
      ElMessageBox.confirm(`确定要取消计划「${plan.planName}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async () => {
        try {
          // 模拟API调用
          console.log('取消计划:', plan)
          
          loadPlanData()
          ElMessage.success('计划已取消')
        } catch (error) {
          console.error('取消计划失败:', error)
          ElMessage.error('操作失败')
        }
      }).catch(() => {})
    }
    
    // 查看计划详情
    const viewPlanDetail = (plan) => {
      currentPlanDetail.value = plan
      planDetailDialogVisible.value = true
    }
    
    // 导入计划
    const importPlan = () => {
      ElMessage.info('导入计划功能开发中')
    }
    
    // 导出计划
    const exportPlan = () => {
      ElMessage.success('计划导出成功')
    }
    
    // 重置计划表单
    const resetPlanForm = () => {
      if (planFormRef.value) {
        planFormRef.value.resetFields()
      }
      planForm.value = {
        planName: '',
        planType: '',
        planScope: [],
        startDate: '',
        endDate: '',
        manager: '',
        remark: ''
      }
    }
    
    // 获取计划类型标签类型
    const getPlanTypeTagType = (type) => {
      const typeMap = {
        'monthly': 'primary',
        'quarterly': 'success',
        'yearly': 'warning',
        'dept': 'info',
        'special': 'danger'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取计划类型文本
    const getPlanTypeText = (type) => {
      const typeMap = {
        'monthly': '月度盘点',
        'quarterly': '季度盘点',
        'yearly': '年度盘点',
        'dept': '部门盘点',
        'special': '专项盘点'
      }
      return typeMap[type] || '未知'
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        'pending': 'info',
        'processing': 'primary',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '未开始',
        'processing': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    }
    
    onMounted(() => {
      loadPlanData()
    })
    
    return {
      searchKeyword,
      planStatus,
      planType,
      planData,
      selectedPlans,
      pagination,
      planDialogVisible,
      planDetailDialogVisible,
      isEditMode,
      planForm,
      planFormRules,
      planFormRef,
      currentPlanDetail,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      createPlan,
      editPlan,
      savePlan,
      startPlan,
      completePlan,
      cancelPlan,
      viewPlanDetail,
      importPlan,
      exportPlan,
      resetPlanForm,
      getPlanTypeTagType,
      getPlanTypeText,
      getStatusTagType,
      getStatusText,
      loadPlanData
    }
  }
}
</script>

<style scoped>
.check-plan-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-controls .el-input {
  width: 200px;
}

.filter-controls .el-select {
  width: 150px;
}

.table-card {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.plan-detail {
  padding: 10px 0;
}

.plan-detail .el-progress {
  display: inline-block;
  width: 150px;
  vertical-align: middle;
  margin-right: 10px;
}

.plan-detail .el-progress + span {
  vertical-align: middle;
}
</style>